import 'package:flutter_admin/api/odoo/mps_replenishment_odoo_api.dart';
import 'package:flutter_admin/models/odoo/mps_replenishment.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'mps_replenishment_dialog.dart';

class MpsReplenishmentList extends StatefulWidget {
  MpsReplenishmentList({Key? key}) : super(key: key);
  @override
  _MpsReplenishmentListState createState() => _MpsReplenishmentListState();
}

class _MpsReplenishmentListState extends State<MpsReplenishmentList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  MpsReplenishment mpsReplenishment = MpsReplenishment();
  List<MpsReplenishment> selectedList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 160,
            label: '产品名称',
            value: mpsReplenishment.productName,
            onSaved: (v) {
              mpsReplenishment.productName = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品编码',
            value: mpsReplenishment.defaultCode,
            onSaved: (v) {
              mpsReplenishment.defaultCode = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('单位')),
        DataColumn(label: Text('可用数')),
        DataColumn(label: Text('在途数')),
        DataColumn(label: Text('需求数')),
        DataColumn(label: Text('订购数')),
      ],
      getCells: (m) {
        MpsReplenishment mpsReplenishment = MpsReplenishment.fromMap(m);
        return [
          DataCell(Text(mpsReplenishment.productName ?? '--')),
          DataCell(Text(mpsReplenishment.defaultCode ?? '--')),
          DataCell(Text(mpsReplenishment.description ?? '--')),
          DataCell(Text(mpsReplenishment.uom ?? '--')),
          DataCell(Text(mpsReplenishment.qtyFree ?? '--')),
          DataCell(Text(mpsReplenishment.qtyTransit ?? '--')),
          DataCell(Text(mpsReplenishment.qtyDemand ?? '--')),
          DataCell(Text(mpsReplenishment.qtyOrder ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
          label: "订购",
          iconData: Icons.view_headline,
          onPressed:
              selectedList.length != 0 ? () => _toOrdered(selectedList) : null,
        ),
        CryButton(
          label: "导出",
          onPressed: () => _generateExcel(),
          iconData: Icons.import_export_outlined,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _toOrdered(List<MpsReplenishment> selectedList) async {
    cryConfirm(context, '确认订购？', (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      ResponseBodyApi responseBodyApi =
          await MpsReplenishmentApi.changeOrdered(['id', 'in', ids]);
      if (responseBodyApi.success!) {
        CryUtils.message('操作成功');
        _query();
      }
    });
  }

  _reset() {
    mpsReplenishment = MpsReplenishment();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await MpsReplenishmentApi.page(
        data: {"page": page, "domainList": mpsReplenishment.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<MpsReplenishment> resultList = [];
    ResponseBodyApi responseBodyApi = await MpsReplenishmentApi.findAll(data: {
      "domainList": mpsReplenishment.toDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
              .map<MpsReplenishment>((e) => MpsReplenishment.fromMap(e))
              .toList() ??
          [];
    }
    return resultList;
  }

  _generateExcel() async {
    List<MpsReplenishment> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'productName',
        'label': '产品名称',
        'columnWidth': 18.0,
      },
      {
        'name': 'defaultCode',
        'label': '产品编码',
        'columnWidth': 18.0,
      },
      {
        'name': 'description',
        'label': '规格型号',
        'columnWidth': 16.0,
      },
      {
        'name': 'uom',
        'label': '单位',
        'columnWidth': 7.0,
      },
      {
        'name': 'qtyFree',
        'label': '可用数',
        'columnWidth': 10.0,
      },
      {
        'name': 'qtyTransit',
        'label': '在途数',
        'columnWidth': 10.0,
      },
      {
        'name': 'qtyDemand',
        'label': '需求数',
        'columnWidth': 10.0,
      },
      {
        'name': 'qtyOrder',
        'label': '订购数',
        'columnWidth': 10.0,
      },
    ];
    Utils.generateExcel(fileName: "物料汇总", configure: map, data: selectedList);
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: MpsDemandLineDialog(),
      ),
    ).then((v) {
      if (v != null) {
        mpsReplenishment = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<MpsReplenishment>((e) => MpsReplenishment.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.handle) {
          _toOrdered(selectedList);
        } else if (v == OperationType.dmsFile) {
          _generateExcel();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length != 0,
          child: ListTile(
            enabled: selectedList.length != 0,
            leading: const Icon(Icons.view_agenda_rounded),
            title: Text('订购'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          child: ListTile(
            leading: const Icon(Icons.import_export_outlined),
            title: Text('导出'),
          ),
        ),
      ],
    );
  }
}
